import { useState } from 'react';
import BigNumber from 'bignumber.js';

type DataConverterReturnType = {
  addresses: string[];
  amounts: BigNumber[];
  convertData: () => void;
};

export default function useDataConverter(
  data: string,
): DataConverterReturnType {
  const [addresses, setAddresses] = useState<string[]>([]);
  const [amounts, setAmounts] = useState<BigNumber[]>([]);

  const convertData = () => {
    const addressRegex = /^0x[a-fA-F0-9]{40}$/;
    const amountRegex = /^\d+$/;

    const newAddresses: string[] = [];
    const newAmounts: BigNumber[] = [];

    data.split('\n').forEach((line) => {
      const [address, amount] = line.trim().split(',');
      const voteCounts = new BigNumber(amount || 0).multipliedBy(
        new BigNumber(1e18),
      );
      if (addressRegex.test(address) && amountRegex.test(amount)) {
        newAddresses.push(address);

        newAmounts.push(voteCounts);
      } else {
        console.log('格式校验失败', address);
      }
    });

    setAddresses(newAddresses);
    setAmounts(newAmounts);
  };

  return { addresses, amounts, convertData };
}
